<?php

namespace catchAdmin\miniapp\controller;

use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\miniapp\model\WechatCloud as wechatCloudModel;
use catchAdmin\wechatopen\model\Applet;
use catchAdmin\wechatopen\model\AdminApplet;
use EasyWeChat\OpenPlatform\Application;
use think\helper\Str;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\ServiceProvider;

class WechatCloud extends CatchController
{
    protected $wechatCloudModel;
    
    public function __construct(WechatCloudModel $wechatCloudModel)
    {
        $this->wechatCloudModel = $wechatCloudModel;
    }

    /**
     * 引入微信控制器的traits
     */
    use \uctoo\library\traits\Wechatopen;
    
    /**
     * 列表
     * @time 2021年03月23日 19:48
     * @param Request $request 
     */
    public function index(Request $request) : \think\Response
    {
        return CatchResponse::paginate($this->wechatCloudModel->getList());
    }
    
    /**
     * 保存信息
     * @time 2021年03月23日 19:48
     * @param Request $request 
     */
    public function save(Request $request) : \think\Response
    {
        return CatchResponse::success($this->wechatCloudModel->storeBy($request->post()));
    }
    
    /**
     * 读取
     * @time 2021年03月23日 19:48
     * @param $id 
     */
    public function read($id) : \think\Response
    {
        return CatchResponse::success($this->wechatCloudModel->findBy($id));
    }
    
    /**
     * 更新
     * @time 2021年03月23日 19:48
     * @param Request $request 
     * @param $id
     */
    public function update(Request $request, $id) : \think\Response
    {
        return CatchResponse::success($this->wechatCloudModel->updateBy($id, $request->post()));
    }
    
    /**
     * 删除
     * @time 2021年03月23日 19:48
     * @param $id
     */
    public function delete($id) : \think\Response
    {
        return CatchResponse::success($this->wechatCloudModel->deleteBy($id));
    }

    /**
     * 获取小程序已有云环境
     * @param Request $request
     * @param Application $app
     */
    public function getCloud(Request $request,Application $app) : \think\Response
    {       //查询管理员当前选中的applet
            $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
            //查询applet
            $applet = Applet::where('appid','=',$adminApplet['appid'])->find();


            if($applet){
                $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
                $cloud_env = $miniapp->register(new ServiceProvider)->cloud_env;
                $res = $cloud_env->getEnvInfo();

                    foreach ($res['info_list'] as $key => $env_info) {
                        $env_info['creator_id'] = $request->user()->id;
                        $env_data = $this->wechatCloudModel->where('env',$env_info['env'])->find();
                        if($env_data){          //已有数据更新
                            $info_data['info_list'] = json_encode($env_info);
                            $info_data['status'] = $env_info['status'];
                            $this->wechatCloudModel->where('env',$env_info['env'])->update($info_data);
                        }else{                  //新增
                            $env_info['appid'] = $applet['appid'];
                            $env_info['info_list'] = json_encode($env_info);

                            $this->wechatCloudModel->save($env_info);
                        }
                    }
                return CatchResponse::success($res,'获取小程序云开发环境成功');
            }else{
                return CatchResponse::fail('获取小程序云开发环境错误');
            }
    }

    /**
     * 创建小程序云环境
     * @param Request $request
     * @param Application $app
     */
    public function createMiniappCloud(Request $request,Application $app) : \think\Response
    {       //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();

        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $cloud_env = $miniapp->register(new ServiceProvider)->cloud_env;
            $res = $cloud_env->checkmobile(true);
            if(true == $res['has_mobile']){
                $result = $cloud_env->createCloudUser();
                if (0 !== $result['errcode']) {
                    return CatchResponse::fail('开通云环境失败');
                }else{
                    //使用appid作为envid
                    $env_id = $applet['appid'] . '-' . Str::random(4, 3);
                    $result = $cloud_env->createEnvAndResource($env_id, $applet['appid']);  //TODO：使用$this->wxResult($result, 'create_env')处理返回结果;
                    return CatchResponse::success($result,'开通云环境成功');
                }
            }else{
                return CatchResponse::success($res,'请小程序管理员先绑定手机');
            }
        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }
}